﻿/**
 * @file fwave_rpcm_test.cpp
 * Copyright (c) Gaaagaa. All rights reserved.
 * 
 * @author  : Gaaagaa
 * @date    : 2020-02-17
 * @version : 1.0.0.0
 * @brief   : 播放 wave-pcm 格式的音频文件（测试 fwave_rpcm_t）。
 */

#include "fwave_pcm.h"
#include "audio_dev.h"

#define SDL_main_h_
#include <SDL/SDL.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

////////////////////////////////////////////////////////////////////////////////

int main(int argc, char * argv[])
{
    x_errno_t xerr_no = X_ERR_UNKNOW;
    x_int32_t xit_err = X_ERR_UNKNOW;

    //======================================

    if (argc < 2)
    {
        printf("Usage: \n\t %s < wave-pcm file path >\n", argv[0]);
        return -1;
    }

    SDL_Init(SDL_INIT_AUDIO);

    //======================================

    fwave_rpcm_t fwave_rpcm;
    xerr_no = fwave_rpcm.open(argv[1]);
    if (XERR_FAILED(xerr_no))
    {
        printf("fwave_rpcm.open([%s]) return error code: %s\n",
               argv[1], fwave_rpcm_t::xerrno_name(xerr_no));
        return -1;
    }
    
    x_uint16_t xut_format = X_AUDIO_S16;
    if (4 == (fwave_rpcm.format().xut_sampbits / 2))
        xut_format = X_AUDIO_S32;
    else if (1 == (fwave_rpcm.format().xut_sampbits / 2))
        xut_format = X_AUDIO_S8;

    //======================================

    adev_playout_t audio_player;
    audio_player.set_callback(
        [](x_handle_t xht_ctxt,
           x_void_t * xmt_data,
           x_int32_t  x1t_size) -> x_void_t
        {
            fwave_rpcm_t * frpcm = (fwave_rpcm_t *)xht_ctxt;

            memset(xmt_data, 0, x1t_size);
            if (frpcm->is_open())
            {
                if (frpcm->read(xmt_data, x1t_size) <= 0)
                {
                    frpcm->seek(0);
                }
            }
        },
        (x_handle_t)&fwave_rpcm);

    //======================================

    xit_err = audio_player.open(
                    -1,
                    (x_uint8_t)fwave_rpcm.format().xut_channels,
                    xut_format,
                    fwave_rpcm.format().xut_samprate);
    if (0 != xit_err)
    {
        printf("audio_player.open(-1, [%d], [%d], [%d]) return error: %d\n",
               fwave_rpcm.format().xut_channels,
               xut_format,
               fwave_rpcm.format().xut_samprate,
               xit_err);
        fwave_rpcm.close();
        return -1;
    }

    //======================================

    system("pause");

    audio_player.close();
    fwave_rpcm.close();

    SDL_Quit();

    //======================================

    return 0;
}
